<template>
  <div class="login-model-content">
    <div class="login-content content-main normal">
      <h3 class="model-type-title">
        <span>{{showLogin|showLOginType}}</span>
        <span class="toggle-type active" @click="handleToggleType">切换为{{!showLogin?'登录':'注册'}}</span>
      </h3>

      <div class="login-registered-wrap">
        <template v-if="showLogin">
          <div class="login-model">
            <el-input placeholder="请输入邮箱" v-model="loginFormData.email" />
            <el-input
              v-model="loginFormData.password"
              type="password"
              maxlength="18"
              placeholder="请输入密码"
              @keydown.enter.native="handleLoginEvent"
            />
            <span @click="handleToForgetPassword" class="active pointer">忘记密码?</span>
            <div class="flex-center">
              <el-button
                class="login-registered-btn"
                :disabled="disabledLoginBtn"
                :loading="loginBtnLoading"
                type="primary"
                @click="handleLoginEvent"
              >登录</el-button>
            </div>
          </div>
        </template>
        <template v-else>
          <div class="registered-model">
            <el-input required placeholder="请输入邮箱" v-model="registerFormData.email" />
            <el-input
              required
              type="password"
              maxlength="18"
              placeholder="请输入密码"
              v-model="registerFormData.password"
            />
            <el-input
              required
              maxlength="16"
              placeholder="请输入用户名"
              v-model="registerFormData.username"
            />
            <div class="email-code flex-top">
              <el-input
                required
                placeholder="请输入验证码"
                maxlength="6"
                v-model="registerFormData.authCode"
              />
              <span
                :class="['getcode-btn', {'theme-bd': sendable}]"
                @click="getAuthCode"
              >{{getCodeText}}</span>
            </div>

            <div class="flex-center">
              <el-button
                type="primary"
                class="login-registered-btn"
                :loading="registerBtnLoading"
                :disabled="disabledRegisterBtn"
                @click="handleRegisterEv"
              >注册</el-button>
            </div>
          </div>
        </template>
      </div>
    </div>
  </div>
</template>

<script>
import API from '~/interface/User';
import Cookie from 'js-cookie';
import FormRules from '~/static/utils/Rules';
export default {
  beforeRouteEnter(to, from, next) {
    next(_self => {
      _self.$utils.userType().then(err => {
        _self.$router.back();
      });
    });
  },

  data() {
    return {
      showLogin: true,
      getCodeText: '获取验证码',
      loginFormData: {
        email: '',
        password: ''
      },
      registerFormData: {
        email: '',
        username: '',
        password: '',
        authCode: ''
      },
      countdown: null,
      sendable: true,
      loginBtnLoading: false,
      registerBtnLoading: false
    }
  },

  computed: {
    disabledLoginBtn() {
      let { trimSpace } = FormRules;
      let { email, password } = this.loginFormData;
      return (trimSpace(email).length === 0) || (trimSpace(password).length < 6);
    },
    disabledRegisterBtn() {
      let { trimSpace } = FormRules;
      let { username, email, password, authCode } = this.registerFormData;
      return (trimSpace(username).length === 0) || (!trimSpace(email).length) || (trimSpace(password).length < 6) || (trimSpace(authCode).length < 6);
    }
  },

  filters: {
    showLOginType(value) {
      return value ? '登录' : '注册'
    }
  },

  methods: {
    handleToggleType() {
      this.showLogin = !this.showLogin;
    },

    // 获取验证码并开始倒计时 120s
    getAuthCode() {
      let _self = this;
      let { checkEmail } = FormRules;
      let { email } = this.registerFormData;
      let countdownNumber = 59;

      if (!checkEmail(email)) {
        this.$message.error('邮箱格式不正确!');
        return false;
      }

      if (this.sendable) {
        this.sendable = false;

        API.getEmailCode({ email }).then(res => {
          // 获取验证码成功以后出现提示并开始倒计时
          this.countdown = setInterval(function () {
            if (countdownNumber) {
              _self.getCodeText = countdownNumber;
              countdownNumber--;
            } else {
              clearInterval(_self.countdown);
              _self.getCodeText = '获取验证码';
              _self.countdown = null;
              this.sendable = true;
            }
          }, 1000);

          this.$message({
            type: 'success',
            message: res.msg
          });
        }).catch(err => {
          this.sendable = true;
        })
      }
    },
    // 用户登录
    handleLoginEvent() {
      let { email, password } = this.loginFormData,
        { checkLength, checkEmail } = FormRules;

      if (!checkEmail(email)) {
        this.$message.error('邮箱格式不正确!');
        return false;
      }

      if (!checkLength(password, 6, 18)) {
        this.$message.error('密码长度不正确!');
        return false;
      }

      // 用户登录
      this.loginBtnLoading = true;
      API.postLogin(this.loginFormData).then(res => {
        Cookie.set('rabbit_token', res.token, { expires: 3 });
        Cookie.set('rabbit_userID', res, { expires: 3 });
        // this.$router.replace('/');
        location.href = '/'; // 登录后刷新页面以及时更新应用数据
        this.loginBtnLoading = false;
      });
    },
    // 用户注册
    handleRegisterEv() {
      let { checkLength, checkEmail } = FormRules,
        { email, username, password, authCode } = this.registerFormData;

      if (!checkEmail(email)) {
        this.$message.error('邮箱格式不正确!');
        return false;
      }

      if (!checkLength(username, 1, 10)) {
        this.$message.error('用户名长度不正确!');
        return false;
      }

      if (!checkLength(password, 6, 18)) {
        this.$message.error('密码长度不正确!');
        return false;
      }

      this.registerBtnLoading = true;
      API.postRegister(this.registerFormData).then(res => {
        this.$message({
          type: 'success',
          message: '您的账户已注册成功, 开始登录叭~'
        });
        // 注册成功后切换为登录
        this.handleToggleType();
        this.registerBtnLoading = false;
      });
    },
    handleToForgetPassword() {
      this.$router.push('/user/sendcode');
    }
  }
}
</script>

<style lang="scss" scoped>
.login-content {
  width: 320px;
  margin: 120px auto 0;

  .model-type-title {
    font-weight: bold;
    font-size: 18px;
    color: #333;

    .toggle-type {
      user-select: none;
      font-weight: normal;
      font-size: 14px;
      cursor: pointer;
    }
  }

  .login-registered-wrap {
    .login-model,
    .registered-model {
      padding-top: 15px;
    }

    .el-input {
      margin-bottom: 10px;
    }

    & /deep/ .el-input__inner {
      height: 35px;
      padding: 0 10px;

      &::placeholder {
        color: #999;
      }
    }

    .login-registered-btn {
      height: 30px;
      margin-top: 10px;
      padding: 0 20px;
      line-height: 30px;
    }
  }
}

.getcode-btn {
  display: inline-block;
  min-width: 90px;
  padding: 0;
  height: 35px;
  line-height: 35px;
  margin-left: 10px;
  text-align: center;
  user-select: none;
  border: 1px solid var(--border);
  color: #666;
  cursor: pointer;
}
</style>